<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退还编码" prop="returnCode">
        <el-input v-model="queryParams.returnCode" placeholder="请输入退还编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="hList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="returnId" />
      <el-table-column label="单据状态" align="center" prop="audiStatus">
        <template slot-scope="scope">
          <button class="but1" v-if="scope.row.audiStatus == 1">待审核</button>
          <button class="but2" v-if="scope.row.audiStatus == 2">已拒绝</button>
          <button class="but3" v-if="scope.row.audiStatus == 3">已审核</button>
          <button class="but4" v-if="scope.row.audiStatus == 4">已撤销</button>
        </template>
      </el-table-column>
      <el-table-column label="退还单号" align="center" prop="returnCode" width="200" />
      <el-table-column label="退还人" align="center" prop="u.nickName" />
      <el-table-column label="退还日期" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="制单时间" align="center" prop="preparedDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.preparedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="prepared" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.audiStatus != 1  || roles == 'common'" size="mini" type="text" icon="el-icon-edit"
            @click="audit(scope.row)">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改资产退还对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="退还部门">
              <el-select placeholder="请选择" value="请选择" v-model="lowerCond.dept_Id" @change="getUserId">
                <el-option v-for="item in lowerBranchList" :key="item.deptId" :value="item.deptId"
                  :label="item.deptName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退还人员">
              <el-select placeholder="请选择" value="请选择" v-model="form.usePerson" @change="selectAsset">
                <el-option v-for="item in lowerStaffList" :key="item.userId" :value="item.userId"
                  :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="存放位置">
              <el-select placeholder="请选择" value="请选择" v-model="formd.locationId">
                <el-option v-for="item in EntrepotList" :key="item.locationId" :value="item.locationId"
                  :label="item.locationName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退还日期">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.returnTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="备注">
              <el-input v-model="form.remark">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="box_scope">
              <el-button v-show="isAdd" style="margin-left: 15px;" type="" plain size="mini"
                @click="add">新增<strong></strong></el-button>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="div-yj">
              <div>
                <el-table :data="assetrkList" border>
                  <el-table-column label="序号" align="center" prop="assetId" />
                  </el-table-column>

                  <el-table-column label="选择资产" align="center" prop="returnCode" :min-width="150">
                    <!-- 使用作用域插槽自定义列内容 -->
                    <template #default="scope">
                      <!-- 在作用域插槽内插入文本框 -->
                      <img @click="zxasset()" class="img1" src="../../../assets/image/搜索.png" />
                      <el-input v-model="scope.row.returnCode"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="资产名称" align="center" prop="assetName" /></el-table-column>
                  <el-table-column label="数量" align="center" prop="num" /></el-table-column>
                  <el-table-column label="金额" align="center" prop="price" /></el-table-column>
                  <el-table-column label="规格" align="center" prop="asseSpec" width="280" /></el-table-column>
                  <el-table-column label="型号" align="center" prop="model"></el-table-column>
                  <el-table-column label="报废日期" align="center" prop="scrapTime" /></el-table-column>

                </el-table>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title2" :visible.sync="open2" width="1200px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-input placeholder="资产名称" maxlength="30" style="width: 200px;" v-model="eamCond.assetName" />&nbsp;
          <el-select placeholder="请选择" value="全部资产类型" v-model="eamCond.TypeId">
            <el-option value="0" label="请选择"></el-option>
            <el-option v-for="item,index in eamTypeList" :key="index" :value="item.typeId"
              :label="item.typeName"></el-option>
          </el-select>&nbsp;
          <el-select placeholder="请选择" value="全部存放位置" v-model="eamCond.locationId">
            <el-option value="0" label="请选择"></el-option>
            <el-option v-for="item,index in EntrepotList" :key="index" :value="item.locationId"
              :label="item.locationName"></el-option>
          </el-select>&nbsp;
          <el-button type="primary" icon="el-icon-search" size="mini" @click="selectIdleEam"
            style="height: 34px;">查询</el-button>
          <el-table :data="assetyjList" border style="padding-top: 10px;" @selection-change="handleSelectionChange"
            ref="uniqueIdentifier">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="资产名称" align="center" prop="assetName" />
            <el-table-column label="资产编码" align="center" prop="assetCodeRule" />
            <el-table-column label="资产类型" align="center" prop="typeName" />
            <el-table-column label="规格" align="center" prop="asseSpec" />
            <el-table-column label="型号" align="center" prop="model" />
            <el-table-column label="资产金额(元)" align="center" prop="price" />
            <el-table-column label="报废日期" align="center" prop="scrapTime" />
            <el-table-column label="数量" align="center" prop="assetNum">
              <template slot-scope="scope">
                <div v-if="!isAdd"><el-input-number v-model="scope.row.num" :min="1"
                    :max="parseInt(scope.row.totalAsset)" @change="handleChange" label="描述文字"></el-input-number>
                </div>
                <div v-if="isAdd"><el-input-number v-model="scope.row.num" :min="1" :max="scope.row.assetNum"
                    @change="handleChange" label="描述文字"></el-input-number>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[3,4,5,6]"
        :page-size="5" layout="total, sizes, prev, pager, next, jumper" :total="pageContent.total"
        @pagination="selectIdleEam">
      </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isOpen">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listH,
    getH,
    delH,
    addH,
    updateH,
    getCode,
    listLowerBranch,
    listLowerStaff,
    listLowerBranchdata,
    listEntrepot,
    listType,
    listIdleEam,
    addD,
    listEam,
    updD,
    updateAsset,
    updateEamD,
    delD
  } from "@/api/eam-xs/return";
  import Cookies from "js-cookie";
  import {
    getInfo
  } from "@/api/login";
  export default {
    name: "H",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 资产退还表格数据
        hList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          returnCode: null,
        },
        // 表单参数
        form: {},
        isAdd: "",
        // 表单校验
        rules: {},
        formd: {
          assetId: null,
          manageId: null,
          count: null,
          locationId: null,
          isdel: 1
        },
        lowerBranchList: {},
        lowerStaffList: {},
        EntrepotList: {},
        lowerCond: {
          dept_Id: "",
          user_Id: "",
          locationId: "",
          claimingDate: "",
        },
        assetrkList: [],
        assetyjList: [],
        eamCond: {
          useStatus: 4,
          locationId: "",
          TypeId: "",
          assetName: "",
          number: 1
        },
        eamTypeList: [],
        selectCheckList: [],
        title2: "",
        open2: false,
        pageContent: {
          total: ''
        },
        codeRule: [],
        selectionList:[],
        manage:[],
        obj:{},
        user:{},
        roles:undefined,
      };
    },
    created() {
      this.getList();
      this.selectEntrepot();
      this.selectType();
      this.selectIdleEam();
      getInfo().then((res) => {
        this.user = res.user;
        this.roles = res.roles;
      });
    },
    methods: {
      /** 查询资产退还列表 */
      getList() {
        this.loading = true;
        listH(this.queryParams).then(response => {
          this.hList = response.rows;
          this.total = response.total;


          this.loading = false;
        });

        listLowerBranch().then(response => {
          this.lowerBranchList = response.data;
        })

        listLowerStaff().then(response => {
          this.lowerStaffList = response.rows;
        })

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = [];
        this.form = {
          returnId: null,
          audiStatus: 1,
          returnCode: null,
          returnTime: null,
          usePerson: null,
          remark: null,
          preparedDate: null,
          prepared: null,
          isdel: 1
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {

        this.ids = selection.map(item => item.returnId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.isAdd = true;
        this.assetrkList = [];
        this.title = "添加资产退还";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        //根据用户查询该用户领用的资产
        this.obj = row;
        let Cond = {};
        Cond.usePerson = row.usePerson;
        listEam(Cond).then((response) => {
          // console.log(JSON.stringify(response));
          this.assetyjList = [];
          // console.log(JSON.stringify(response.rows));
          for (let i = 0; i < response.rows.length; i++) {
            this.assetyjList.push({
              "assetName": response.rows[i].eamAsset.assetName,
              "asseSpec": response.rows[i].eamAsset.asseSpec,
              "model": response.rows[i].eamAsset.model,
              "price": response.rows[i].eamAsset.price,
              "scrapTime": response.rows[i].eamAsset.scrapTime,
              "assetNum": response.rows[i].eamAsset.assetNum,
              "assetCodeRule": response.rows[i].eamAsset.assetCode,
              "typeName": response.rows[i].eamType.typeName,
              "num": 1,
              "assetId": response.rows[i].eamAsset.assetId,
              "manageId": response.rows[i].eamManageD.manageId,
            });
          }
        })
        console.log("row"+JSON.stringify(row));
        this.lowerCond.dept_Id = row.dept.deptId;
        this.formd.locationId = row.eamLocation.locationId;
        this.selectCheckList = [];
        this.assetrkList = [];
        this.selectCheckList.push(row);
        this.assetrkList.push({
          "assetId": row.eamAsset.assetId,
          "returnCode": row.returnCode,
          "assetName": row.eamAsset.assetName,
          "num": row.eamReturnD.count,
          "price": row.eamAsset.price,
          "asseSpec": row.eamAsset.asseSpec,
          "model": row.eamAsset.model,
          "scrapTime": row.eamAsset.scrapTime,
          "locationId" : row.eamLocation.locationId,
        })
        this.reset();
        this.form = row;
        this.open = true;
        this.title = "修改资产退还";
        setTimeout(() => {
          this.$refs.uniqueIdentifier.clearSelection();
        }, 1000)
      },
      /** 提交按钮 */
      submitForm() {
        if(this.roles == "common"){
          if(this.user.userId != this.obj.prepared){
            this.$message.warning("您没有此权限");
            return;
          }
        }
        if (this.isAdd) {
          // this.assetrkList.forEach((item) => {
          //   this.form.returnCode = item.assetCode;
          //   this.form.preparedDate = this.form.returnTime;
          //   this.form.prepared = Cookies.get("username");
          //   addH(this.form).then((resp) => {})
          //   this.formd.assetId = item.assetId;
          //   this.formd.manageId = item.assetCode;
          //   this.formd.count = item.num;
          //   this.formd.locationId = item.locationId;
          //   addD(this.formd).then((response) => {
          //     if (response.code == 200) {
          //       this.$modal.msgSuccess("添加成功");
          //       this.open = false;
          //       this.getList();
          //     }
          //   })
          // })
        } else {
          // console.log("C" + JSON.stringify(this.selectCheckList[0]));
          for (let i = 0; i < this.assetrkList.length; i++) {
            if (this.assetrkList.length == 1) {
              this.reset()
              this.formd.count = this.assetrkList[i].num;
              this.formd.assetId = this.assetrkList[i].assetId;
              this.formd.manageId = this.selectCheckList[0].returnCode;
              this.form.returnId = this.selectCheckList[0].returnId;
              this.formd.isdel = null;
              this.form.remark = this.selectCheckList[0].remark;
              this.form.usePerson = this.selectCheckList[0].usePerson;
              this.form.returnTime = this.selectCheckList[0].returnTime;
              this.form.preparedDate = this.form.returnTime;
              this.form.isdel = null;
              this.form.audiStatus = null;
              if (this.selectCheckList[0].eamAsset.assetId != this.assetrkList[i].assetId) {
                // console.log("Trk" + JSON.stringify(this.assetrkList[i]));
                let assetCond = {};
                assetCond.assetNum = this.selectCheckList[0].eamReturnD.count;
                assetCond.assetId = this.selectCheckList[0].eamAsset.assetId;

                for (let i = 0; i < this.assetyjList.length; i++) {
                  if (this.assetyjList[i].assetId == this.selectCheckList[0].eamReturnD.assetId) {
                    let assetDCond = {};
                    assetDCond.manageId = this.assetyjList[i].manageId;
                    assetDCond.number = this.selectCheckList[0].eamReturnD.count;
                    updateEamD(assetDCond).then((response) => {

                    })
                  }
                }
                updateAsset(assetCond).then((response) => {

                })
              }
              updateH(this.form).then((response) => {

              })
              updD(this.formd).then((response) => {
                if (response.code == 200) {
                  this.open = false;
                  this.$modal.msgSuccess("资产" + this.formd.assetId + "已修改");
                  setTimeout(() => {
                    this.getList();
                  }, 1000)
                }
              })
            } else {
              //修改长度大于1
              console.log(i+JSON.stringify(this.assetrkList[i]));
              // this.form
              if(i != 0){
                this.reset();
                let randomNum = "THD" + Math.floor(Math.random() * 10000000000000000);
                this.form.returnCode = randomNum;
                this.form.remark = this.selectCheckList[0].remark;
                this.form.audiStatus = 1;
                this.form.prepared = Cookies.get("username");
                this.form.usePerson = this.selectCheckList[0].usePerson;
                this.form.returnTime = this.selectCheckList[0].returnTime;
                this.form.preparedDate = this.form.returnTime;
                addH(this.form).then((response) =>{})

                this.formd.manageId = randomNum;
                this.formd.assetId = this.assetrkList[i].assetId;
                this.formd.count = this.assetrkList[i].num;
                addD(this.formd).then((response) =>{
                  if (response.code == 200) {
                    this.open = false;
                    this.$modal.msgSuccess("资产" + this.formd.assetId + "已修改");
                    setTimeout(() => {
                      this.getList();
                    }, 1000)
                  }
                })
              }
            }
          }
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        if(this.roles == "common"){
          if(this.user.userId != this.obj.prepared){
            this.$message.warning("您没有此权限");
            return;
          }
        }
        const returnIds = row.returnId || this.ids;
        let manageD = {};
        manageD.manageId = row.returnCode
        this.$modal.confirm('是否确认删除资产退还编号为"' + returnIds + '"的数据项？').then(function() {
          return delH(returnIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('return/h/export', {
          ...this.queryParams
        }, `h_${new Date().getTime()}.xlsx`)
      },
      add() {
        if (this.isAdd) {
          this.assetrkList.push({})
        }
        getCode().then((response) => {
          this.codeRule.push(response);
        })
      },
      getUserId() {
        listLowerBranchdata(this.lowerCond.dept_Id).then(response => {
          this.lowerStaffList = response.data;
        })
      },
      selectEntrepot() {
        listEntrepot().then((response) => {
          this.EntrepotList = response.rows;
        })
      },
      zxasset() {
        this.open2 = true;
        this.title2 = "选择资产";
        for (let i = 0; i < this.assetyjList.length; i++) {
          if (this.selectCheckList[0].eamAsset.assetId == this.assetyjList[i].assetId) {
            setTimeout(() => {
              this.$refs.uniqueIdentifier.toggleRowSelection(this.assetyjList[i], true);
            }, 1000)
          }
        }
      },
      selectType() {
        listType().then((response) => {
          this.eamTypeList = response.rows;
        })
      },
      selectIdleEam() {
        this.eamCond.locationId = this.eamCond.locationId == 0 ? "" : this.eamCond.locationId;
        this.eamCond.TypeId = this.eamCond.TypeId == 0 ? "" : this.eamCond.TypeId;
        listIdleEam(this.eamCond).then((response) => {
          this.assetyjList = response.rows;
          for (let i = 0; i < this.assetyjList.length; i++) {
            this.assetyjList[i].typeName = response.rows[i].eamType.typeName;
          }
          this.pageContent.total = response.total;
          this.assetyjList = this.assetyjList.map(item => ({
            ...item, // 使用展开语法保留原始对象的所有属性
            num: 1, // 添加 num 字段并设置初始值为 1
            assetCodeRule: item.assetCode,
          }));
        })
      },
      handleSelectionChange(selection) {
        for (let i = 0; i < selection.length; i++) {
          if (this.codeRule != "") {
            selection[i].assetCode = (this.codeRule[i].msg);
          }
        }
        this.ids = selection.map(item => item.manageId);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
        if (selection != "") {
          this.assetrkList = selection;
        }
      },
      cancel2() {
        this.open2 = false;
        this.reset();
      },
      isOpen() {
        this.open2 = false;
        if (this.assetrkList.length > 1) {
          for (let i = 0; i < this.assetrkList.length; i++) {
            if (i != 0) {
              this.selectCheckList.push(this.assetrkList[i])
            }
          }
        }
      },
      handleSizeChange(val) {
        this.selectIdleEam();
      },
      handleCurrentChange(val) {

      },
      handleSizeChange(val) {
        this.selectIdleEam();
      },
      handleChange(value) {

      },
      audit(row) {
        let assetReturn = {};
        assetReturn.returnId = row.returnId;
        assetReturn.audiStatus = 3;
        updateH(assetReturn).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("序号为:" + row.returnId + "已审核")
            this.getList();
          }
        })
      },
      selectAsset() {
        let Cond = {};
        Cond.usePerson = this.form.usePerson;
        listEam(Cond).then((response) => {
          this.assetyjList = [];
          for (let i = 0; i < response.rows.length; i++) {
            this.assetyjList.push({
              "assetName": response.rows[i].eamAsset.assetName,
              "asseSpec": response.rows[i].eamAsset.asseSpec,
              "model": response.rows[i].eamAsset.model,
              "price": response.rows[i].eamAsset.price,
              "scrapTime": response.rows[i].eamAsset.scrapTime,
              "assetNum": response.rows[i].eamAsset.scrapTime,
              "assetCodeRule": response.rows[i].eamAsset.assetCode,
              "typeName": response.rows[i].eamType.typeName,
              "num": 1
            });
          }
        })
      }
    }
  };
</script>
<style>
/* 单据状态 */
  .but1 {
    color: sandybrown;
    border-radius: 30px;
    font-size: 11px;
    background-color: #ffdcbc;
    border: 1px solid sandybrown;
  }

  .but2 {
    color: #aa3800;
    border-radius: 30px;
    font-size: 11px;
    background-color: #ff8d6a;
    border: 1px solid #ff8d6a;
  }

  .but3 {
    color: #4ab0f9;
    border-radius: 30px;
    font-size: 11px;
    background-color: #e6eff4;
    border: 1px solid #4ab0f9;
  }

  .but4 {
    color: #550000;
    border-radius: 30px;
    font-size: 11px;
    background-color: #d1d9dd;
    border: 1px solid #550000;
  }

  .el-form-item .el-input {
    width: 160px;
  }

  .img1 {
    height: 20px;
    position: absolute;
    z-index: 1;
    /* 设置图片的z-index值高于其他元素 */
    right: 15px;
    top: 18px;
    cursor: pointer;
    /* 将鼠标指针设置为手形 */
    transition: background-color 0.3s ease;
    /* 添加过渡效果 */
  }

  .el-input-number {
    width: 120px;
  }
</style>
